package com.ruoyi.web.controller.system;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.ruoyi.system.domain.*;
import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.TemplateExportParams;
import com.ruoyi.system.domain.AppliDetail;
import com.ruoyi.system.domain.Outing;
import com.ruoyi.system.domain.Warehouse;
import com.ruoyi.system.domain.Warehousing;
import com.ruoyi.system.service.IOutingService;
import com.ruoyi.system.service.IWarehousingService;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.system.domain.Purchase;
import com.ruoyi.system.service.IPurchaseService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

import javax.servlet.http.HttpServletResponse;

/**
 * 采购单Controller
 *
 * @author ruoyi
 * @date 2021-05-06
 */
@RestController
@RequestMapping("/system/purchase")
public class PurchaseController extends BaseController {
    @Autowired
    private IPurchaseService purchaseService;
    @Autowired
    private IWarehousingService warehousingService;
    @Autowired
    private IOutingService outingService;


    //采购单列表
//    @PreAuthorize("@ss.hasPermi('system:purchase:list')")
    @GetMapping("/list")
    public TableDataInfo list(Purchase purchase) {
        startPage();
        List<Purchase> list = purchaseService.selectPurchaseList(purchase);
        if (list!=null&&list.size()>0) {
            for (int i = 0; i < list.size(); i++) {
                Purchase purchase1 = list.get(i);
                if (purchase1.getFullAmount() == 0.0) {
                    purchase1.setPaidPercent(0.0);
                } else {
                    purchase1.setPaidPercent(new BigDecimal(new Double((purchase1.getBePaid() + purchase1.getPaid() + purchase1.getAftPaid()) / purchase1.getFullAmount()).toString()).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());
                }
                if (null!=purchase1.getAftPaidTime()){
                    purchase1.setPayTime(purchase1.getAftPaidTime());
                }else if (null==purchase1.getPayTime()){
                    purchase1.setPayTime(purchase1.getBePaidTime());
                }
                if(null==purchase1.getShipping()){
                    purchase1.setShipping(0.0);
                }
                //金额加上运费
                purchase1.setFullAmount(new BigDecimal(new Double(purchase1.getFullAmount()+purchase1.getShipping()).toString()).doubleValue());

            }
        }
        return getDataTable(list);
    }

    //获取材料采购单详情
//    @PreAuthorize("@ss.hasPermi('system:purchase:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return AjaxResult.success(purchaseService.selectPurchaseById(id));
    }

    @GetMapping(value = "sum/{id}")
    public AjaxResult selectPurchaseSum(@PathVariable("id") Long id) {
        return AjaxResult.success(purchaseService.selectPurchaseSum(id));
    }

    //新增采购单
// @PreAuthorize("@ss.hasPermi('system:purchase:add')")
    @Log(title = "采购单", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody Purchase purchase) {
        return toAjax(purchaseService.insertPurchaseRecord(purchase));
    }


    //删除采购单材料
    @GetMapping("/delete")
    public AjaxResult deleteMat(long id) {
        return toAjax(purchaseService.deleteMat(id));
    }


    //编辑采购单
    //@PreAuthorize("@ss.hasPermi('system:purchase:edit')")
    @Log(title = "采购单", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody Purchase purchase) {
        return toAjax(purchaseService.updatePurchase(purchase));
    }


    //生成出入库单
    @GetMapping("/addInMonad/{pur_id}")
    public AjaxResult addInMonad(@PathVariable("pur_id") Long pur_id) {

        return toAjax(purchaseService.addInMonad(pur_id));
    }

    //生成出库单
    @GetMapping("/addOutMonad/{pur_id}")
    public AjaxResult addOutMonad(@PathVariable("pur_id") Long pur_id) {
        int i = purchaseService.addOutMonad(pur_id);
        if (i > 0) {
            return success("生成出库单成功");
        } else {
            return error("生成出库单失败，请确保已生成入库单，且入库单材料已全部入库");
        }

    }
    //       跳转出库单
//    @GetMapping("/selectOut/{pur_id}")
//    public AjaxResult selectOut(@PathVariable("pur_id") Long pur_id)
//    {
//
//        return toAjax(purchaseService.selectOut(pur_id));
//    }
//    //跳转出库单
//    @GetMapping("/selectIn/{pur_id}")
//    public AjaxResult selectIn(@PathVariable("pur_id") Long pur_id)
//    {
//
//        return toAjax(purchaseService.selectIn(pur_id));
//    }


    /**
     * 导出采购单列表
     */

    @Log(title = "采购单", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(Purchase purchase) {
        List<Purchase> list = purchaseService.selectPurchaseList(purchase);
        ExcelUtil<Purchase> util = new ExcelUtil<Purchase>(Purchase.class);
        return util.exportExcel(list, "采购单数据");
    }


    /**
     * 删除采购单
     */
    @Log(title = "采购单", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(purchaseService.deletePurchaseByIds(ids));
    }

    //材料请购
    @PostMapping("/uplod")
    @CrossOrigin
    public void uplod(Long id, HttpServletResponse response) {
        try {
            Purchase Purchase = purchaseService.selectPurchaseById(id);
            List<Object> list = new ArrayList<>();
            // 表一数据
            Double sum = 0.0;
            DecimalFormat df = new DecimalFormat("#.##");
            df.setRoundingMode(RoundingMode.HALF_UP);
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
            for (int i = 0; i < Purchase.getPurchaseRecords().size(); i++) {
                Map<String, Object> map = new HashMap<>();
                map.put("id", i + 1);
                if (null != Purchase.getPurchaseRecords().get(i).getmName())
                    map.put("mName", Purchase.getPurchaseRecords().get(i).getmName());
                else map.put("mName", "");
                if (null != Purchase.getPurchaseRecords().get(i).getMdSpecifications() && null != Purchase.getPurchaseRecords().get(i).getMdSpecifications()) {
                    map.put("name", Purchase.getPurchaseRecords().get(i).getMdSpecifications() + "/" + Purchase.getPurchaseRecords().get(i).getmModel());
                } else map.put("name", "");
                if (null != Purchase.getPurchaseRecords().get(i).getmUnit())
                    map.put("mUnit", Purchase.getPurchaseRecords().get(i).getmUnit());
                else map.put("mUnit", "");
                if (null != Purchase.getPurchaseRecords().get(i).getMdBrand())
                    map.put("mdBrand", Purchase.getPurchaseRecords().get(i).getMdBrand());
                else map.put("mdBrand", "");
                if (null != Purchase.getPurchaseRecords().get(i).getMdBusiness())
                    map.put("mdBusiness", Purchase.getPurchaseRecords().get(i).getMdBusiness());
                else map.put("mdBusiness", "");
                if (null != Purchase.getPurchaseRecords().get(i).getCommBus()) {
                    if (Integer.valueOf(Purchase.getPurchaseRecords().get(i).getCommBus()) == 0)
                        map.put("commBus", "否");
                    if (Integer.valueOf(Purchase.getPurchaseRecords().get(i).getCommBus()) == 1)
                        map.put("commBus", "是");
                } else map.put("commBus", "");

                if (null != Purchase.getPurchaseRecords().get(i).getMdSum())
                    map.put("mdSum", Purchase.getPurchaseRecords().get(i).getMdSum());
                else map.put("mdSum", 0);
                if (null != Purchase.getPurchaseRecords().get(i).getMdPrice())
                    map.put("mdPrice", Purchase.getPurchaseRecords().get(i).getMdPrice());
                else map.put("mdPrice", 0);
                if (null != Purchase.getPurchaseRecords().get(i).getMdPrice()) {
                    double sum1 = Purchase.getPurchaseRecords().get(i).getMdSum() * Purchase.getPurchaseRecords().get(i).getMdPrice();
                    map.put("sum1", df.format(new BigDecimal(sum1+"")));
                } else map.put("sum1", 0);
                sum += Double.valueOf(map.get("sum1") + "");
                map.put("sumPurchase", Purchase.getPurchaseRecords().get(i).getSum());
                list.add(map);
            }
            for (int i = list.size(); i < 14; i++) {
                Map<String, Object> map = new HashMap<>();
                map.put("id", list.size() + 1);
                map.put("mName", "");
                map.put("name", "");
                map.put("mUnit", "");
                map.put("mdBrand", "");
                map.put("mdBusiness", "");
                map.put("commBus", "");
                map.put("mdSum", "");
                map.put("mdPrice", "");
                map.put("sum", "");
                list.add(map);
            }
            // 表格使用的数据
            Map map = new HashMap();
            if (Purchase.getShipping() != null) {
                sum += Purchase.getShipping();
                map.put("shipping", "￥" + Purchase.getShipping());//放入表一数据
            } else {
                map.put("shipping", "￥" + 0);//放入表一数据
            }
                map.put("proName", Purchase.getProName());
                map.put("proNumber", Purchase.getProNumber());
                map.put("deliveryReq", Purchase.getDeliveryReq());
                map.put("requisitionDate", simpleDateFormat.format(Purchase.getRequisitionDate()));
                map.put("data", list);//放入表一数据
                map.put("sum", "￥" + df.format(new BigDecimal(sum)));//放入表一数据
                // 获取模板文件
                //读取模板
                TemplateExportParams params = new TemplateExportParams("/home/ruoyi/excel/材料采购单.xls");
                Workbook workbook = ExcelExportUtil.exportExcel(params, map);
                workbook.write(response.getOutputStream());
                workbook.close();
            } catch(Exception e){
                e.printStackTrace();
            }
        }


        /**
         * 查看项目能不能修改项目
         */

        @GetMapping("/stateOfPurchase/{pur_id}")
        public AjaxResult stateOfPurchase (@PathVariable("pur_id") Long pur_id){
            int i = purchaseService.stateOfPurchase(pur_id);
            if (i > 0) {
                return success();
            } else {
                return success("无法修改，已经材料出库或者入库");
            }
        }


    }

